<template>
  <div class="search-result-container">
    <!-- 点击实现后退效果 -->
    <van-nav-bar title="搜索结果" left-arrow @click-left="$router.back()" fixed />
   <van-list v-model="loading" :finished='finished' :immediate-check='false' @load="onload">
     <art-item v-for="item in searchLists" :key="item.art_id" :article='item' :closeable='false'></art-item>
   </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/searchAPI.js'
import ArtItem from '@/components/ArtItem/ArtItem.vue'

export default {
  name: 'SearchResult',
  props: ['kw'],
  data () {
    return {
      // 默认请求第一页的结果
      page: 1,
      searchLists: [],
      loading: false,
      finished: false,
      preKw: ''
    }
  },
  created () {
    this.initSearchLists()
  },
  activated () {
    if (this.preKw !== '' && this.kw !== this.preKw) {
      this.page = 1
      this.searchLists = []
      this.loading = false
      this.finished = false
      this.initSearchLists()
    }
  },
  deactivated () {
    this.preKw = this.kw
  },
  methods: {
    async initSearchLists () {
      const { data: res } = await getSearchResult(this.kw, this.page)
      if (res.message === 'OK') {
        // 1.拼接 ‘旧’+‘新’88
        this.searchLists = [...this.searchLists, ...res.data.results]
        // 2.将loading状态重置为false
        this.loading = false
        // 3.如果请求数据为空，则没有更多数据了，finished属性设置为true
        if (res.data.results.length === 0) {
          this.finished = true
        }
        // 4.数据请求完成，为下次请求做准备，请求下一页的数据
        this.page += 1
      }
    },
    // 触发了上拉加载
    onload () {
      this.initSearchLists()
    }
  },
  components: {
    ArtItem
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
